from fastapi import APIRouter, Depends, Query, Path

from src.base.beans import Rest
from src.config.auth import auth_depend
from src.config.db import DbSession
from src.config.log import log_depend
from src.dao.sys_tenant_dao import get_tenant_by_id, get_tenant_list_by_condition, get_tenant_page_by_condition, \
    insert_tenant, update_tenant, delete_tenants
from src.domain.sys_tenant import SysTenantReq, SysTenant

router = APIRouter(prefix='/sys/tenant', dependencies=[Depends(auth_depend), Depends(log_depend)], tags=["租户管理"])


@router.get("/get_by_id/{id}", summary="根据ID查询", )
async def get_by_id(dbSession: DbSession, id: str = Path()):
    dept = await get_tenant_by_id(dbSession, int(id))
    return Rest.ok(dept)


@router.get("/list", summary="根据条件查询用户列表", )
async def get_list_by_condition(dbSession: DbSession, entity: SysTenantReq = Query(default=None)):
    result = await get_tenant_list_by_condition(dbSession, entity)
    return Rest.ok(result)


@router.get("/page", summary="根据条件分页查询用户列表", )
async def get_page_by_condition(dbSession: DbSession, entity: SysTenantReq = Query(default=None)):
    result = await get_tenant_page_by_condition(dbSession, entity)
    return Rest.ok(result)


@router.post("/create", summary="新增", )
async def create(dbSession: DbSession, entity: SysTenantReq):
    await insert_tenant(dbSession, entity)
    return Rest.ok()


@router.put("/edit", summary="修改", )
async def edit(dbSession: DbSession, entity: SysTenantReq):
    result = await update_tenant(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.post("/create_edit", summary="新增或修改", )
async def create_edit(dbSession: DbSession, entity: SysTenantReq):
    result = 1
    if entity.tenant_id is None:
        await insert_tenant(dbSession, entity)
    else:
        result = await update_tenant(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.delete("/delete", summary="删除", )
async def delete(dbSession: DbSession, ids: list[str] = Query()):
    result = await delete_tenants(dbSession, [int(id) for id in ids])
    return Rest.ok() if result > 0 else Rest.fail()
